package com.vtest.quartz.task.report;

import com.vtest.quartz.domain.job.SysJob;
import com.vtest.quartz.domain.vtest.report.CPPostErrorEntity;
import com.vtest.quartz.domain.vtest.report.HoldBinDataEntity;
import com.vtest.quartz.domain.vtest.report.HoldReasonEntity;
import com.vtest.quartz.domain.vtest.report.HoldSummaryEntity;
import com.vtest.quartz.service.vtest.report.CommonReportService;
import com.vtest.quartz.utils.MailHelper;
import com.vtest.quartz.utils.excel.ExcelUtil;
import com.vtest.quartz.utils.others.StringUtils;
import com.vtest.quartz.utils.vtest.WeiXinRobot;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: Quartz
 * @author: tiger
 * @create: 2024-12-24 13:23
 * @Description :通用报表任务
 */
@Slf4j
@Component("CommonReport")
public class CommonReport {

    @Autowired
    private CommonReportService commonService;

    /*
     * CP过账报错报表
     */
    public void sendHoldNJReport() {
        log.debug("[CP过账报错报表] 任务开始执行");
        List<CPPostErrorEntity> cpPostErrorInfoList = commonService.getCPPostErrorInfo();
        //生成excel
        ExcelUtil<CPPostErrorEntity> util = new ExcelUtil<CPPostErrorEntity>(CPPostErrorEntity.class);
        util.exportExcel(cpPostErrorInfoList, "CP过账报错报表", StringUtils.EMPTY, true);

        //转化为图片
        String imgFile = StringUtils.substringBefore(util.downFile, util.downFile.lastIndexOf("\\"))
                + UUID.randomUUID() + ".png";
        if (ExcelUtil.convertExcelToPng(util.downFile, imgFile)) {
            //发送图片和excel到企业微信
            //发送图片
            String webhook = "30c08991-30b5-4bee-8aaf-17b5cc5be410";
            WeiXinRobot robot = new WeiXinRobot(webhook);
            robot.sendImage(imgFile);

            //发送excel
            robot.sendFile(webhook, util.downFile);

            //@所有
            robot.textSend("@所有人", null);


        }

        log.debug("[CP过账报错报表] 任务开始结束");
    }

    /*
     * 廖海娟 要求每天 3、9、15、21 点发送消息至 企业微信群
     */
    public void sendInformationToWXByRobot() {

        String webhook = "21453a4b-b1d2-4eac-8b8b-88ea90a39d24";
        WeiXinRobot robot = new WeiXinRobot(webhook);
        LocalDateTime date = LocalDateTime.now();
        int hour = date.getHour();
        if (hour == 3 || hour == 9 || hour == 15 || hour == 21) {
            robot.textSend("到点了！及时关注线上 FUA  CH2  次好品固定site 现象", null);

            robot.textSend("@所有人", null);
        }
    }

    /*
     * 王子敬 要求 发送FTHold报表
     * lot - 查询的Vtlot
     */
    public void sendFTHoldReport(String code, String lot) {
        log.debug("[{} FT HOLD 报表] 任务开始执行 {}", code, lot);

        LocalDateTime now = LocalDateTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = dateTimeFormatter.format(now);

        String key = "9b7b21f1-706e-4d31-9f2a-c49dc3739f08";
        WeiXinRobot robot = new WeiXinRobot(key);
        //查询低良数据
        List<Map<String, String>> holdLotInfoList = commonService.getHoldLotInfo(code, lot);

        for (Map<String, String> map : holdLotInfoList) {
            String lotNum = map.get("LotNum");
            String ft = map.get("FromStepCode");
            String device = map.get("CustPart");
            String custLot = map.get("CustLotNum");
            robot.textSendMarkdown("LotNum[" + lotNum + "] - 开始");

            //获取HoldReason报表的数据
            List<HoldReasonEntity> holdReasonReportList = commonService.getHoldReasonReport(lotNum, ft);

            //生成 HoldReason excel
            ExcelUtil<HoldReasonEntity> holdReasonUtil = new ExcelUtil<HoldReasonEntity>(HoldReasonEntity.class);
            holdReasonUtil.exportExcel(holdReasonReportList,
                    code + "_" + device + "_" + custLot + "_" + lotNum + "_" + ft + "_Hold_Reason.xlsx",
                    StringUtils.EMPTY, true);

            //获取LotSummary报表的数据
            List<HoldSummaryEntity> SummaryReportList = commonService.getFTHoldSummaryReport(lotNum, ft);

            //生成 HoldSummary excel
            ExcelUtil<HoldSummaryEntity> holdSummaryUtil = new ExcelUtil<>(HoldSummaryEntity.class);
            holdSummaryUtil.exportExcel(SummaryReportList,
                    code + "_" + device + "_" + custLot + "_" + lotNum + "_" + ft + "_Hold_Summary.xlsx",
                    StringUtils.EMPTY, true);


            //获取BinData报表的数据
            List<HoldBinDataEntity> binDataReportList = commonService.getFTHoldBinDataReport(lotNum, ft);

            //生成 BinData excel
            ExcelUtil<HoldBinDataEntity> binDataUtil = new ExcelUtil<>(HoldBinDataEntity.class);
            binDataUtil.exportExcel(binDataReportList,
                    code + "_" + device + "_" + custLot + "_" + lotNum + "_" + ft + "_Hold_BinData.xlsx",
                    StringUtils.EMPTY, true);

            File holdReasonFile = new File(holdReasonUtil.downFile);
            File holdSummaryFile = new File(holdSummaryUtil.downFile);
            File binDataFile = new File(binDataUtil.downFile);
            if (holdReasonFile.exists() && holdSummaryFile.exists() && binDataFile.exists()) {
                //生成文件成功
                //更新文件的最后抓取时间
                if (!StringUtils.isNotEmpty(lot)) commonService.updateFTHoldFinalSendTime(code, time);

                //发送邮件
                List<String> mailList = new ArrayList<>();
                mailList.add(holdReasonUtil.downFile);
                mailList.add(holdSummaryUtil.downFile);
                mailList.add(binDataUtil.downFile);

                MailHelper helper = new MailHelper();
                //helper.sendMail();
                helper.sendMail("tao.zhu@v-test.com.cn;feng.yang@v-test.com.cn;kai.deng@v-test.com.cn;william.shang@v-test.com.cn;vtestshiftpte4@v-test.com.cn;zijing.wang@v-test.com.cn;ptenjp2@v-test.com.cn"
                        , "ruhu.wang@v-test.com.cn"
                        , code + "_" + device + "_" + custLot + "_" + lotNum + "_" + ft + "_Hold_Lots.xlsx"
                        , code + "_" + device + "_" + custLot + "_" + lotNum + "_" + ft + "_Hold_Lots.xlsx 测试 Summary Report 已附加 数据如下，请协助review指示灯放行"
                        , mailList);
            }


        }


    }

    public static void main(String[] args) {
        String webhook = "21453a4b-b1d2-4eac-8b8b-88ea90a39d24";
        WeiXinRobot robot = new WeiXinRobot(webhook);

        //robot.textSend("到点了！及时关注线上 FUA  CH2  次好品固定site 现象", null);

        //robot.textSend("@所有人", null);
        int year = 2025;
        int week = 1;

        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);

        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);

        System.out.println(getLastDayOfWeek(cal.getTime()));


    }

    // 获取当前时间所在周的结束日期
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
        return c.getTime();
    }

}
